import { defineStore } from 'pinia';
import pinia from '../index';
import { userLogin, refreshUserInfo } from '@/api/user';
import { UserState } from '@/types';

export const useUserStoreHook = defineStore('User', {
	state: (): UserState => ({
		username: '',
		accessToken: '',
		roles: ['common']
	}),
	getters: {},
	actions: {
		storeUserLogin(data) {
			return userLogin(data).then((res) => {
				this.username = res.username;
				this.roles = res.roles;
				this.accessToken = res.accessToken;
				return res;
			});
		},
		stroeRefreshUserInfo() {
			if (this.username == '大伟' && this.accessToken != '') {
				refreshUserInfo({
					accessToken: this.accessToken
				})
					.then((res) => {
						this.username = res.username;
						this.roles = res.roles;
						this.accessToken = res.accessToken;
					})
					.catch(() => {
						this.accessToken = '';
					});
			}
		}
	},
	persist: {
		key: 'User',
		storage: localStorage,
		omit: ['accessToken']
	}
});
const useUserStore = (): ReturnType<typeof useUserStoreHook> => {
	return useUserStoreHook(pinia);
};
export default useUserStore;
